#!/usr/bin/env bash

set -e

# ./add_channel.sh white 白耶耶 '#FEBF99' cqjy 10902
if [ $# -lt 5 ]; then
	echo "Usage: $0 <brand> <name> <color> <factory> <barcode>"
	exit
fi

MYSQL_WATERFALL='mysql --defaults-group-suffix=.wf.slave --column-names=false'
MYSQL_LAKE='mysql --defaults-group-suffix=.lk.admin --column-names=false'

BRAND=$1
NAME=$2
COLOR=$3
FACTORY=$4
BARCODE=$5
BY='admin'

IFS=$'\t' read -r AK SK <<< $(
	${MYSQL_WATERFALL} ${BRAND}_factory -e'
		SELECT k.`access_key`, k.`secret_key`
		FROM `fty_key` k JOIN `fty_factory` f ON k.factory_id = f.id
		WHERE f.`code` = '\'"${FACTORY}"\'
)
echo ${AK} ${SK}

CHANNEL_ID=$(${MYSQL_LAKE} lk_${FACTORY} -e'
	SELECT `id` FROM `sys_channel` WHERE `code` = '\'"${BRAND}"\'
)
if [ -z ${CHANNEL_ID} ]; then
	CHANNEL_ID=$(${MYSQL_LAKE} lk_${FACTORY} -e'
		INSERT INTO `sys_channel` (`code`, `name`, `config`, `type`, `create_by`, `modify_by`) VALUES ('\'${BRAND}\'', '\'${NAME}\'', JSON_OBJECT(
			'\'name\'', '\'${NAME}\'',
			'\'color\'', '\'${COLOR}\'',
			'\'barcode\'', '\'${BARCODE}\'',
			'\'baseurl\'', '\'"https://${BRAND}.inf-sea.net"\''
		), '\'WATERFALL\'', '\'${BY}\'', '\'${BY}\'');
		SELECT @@last_insert_id;
	')
fi;
${MYSQL_LAKE} lk_${FACTORY} -e'SELECT * FROM `sys_channel` WHERE `code` = '\'${BRAND}\' | cat

AUTH_ID=$(${MYSQL_LAKE} lk_${FACTORY} -e'
	SELECT `id` FROM `sys_channel_auth` WHERE `channel_id` = '"${CHANNEL_ID}"
)
if [ -z ${AUTH_ID} ]; then
	${MYSQL_LAKE} lk_${FACTORY} -e'
		INSERT INTO `sys_channel_auth` (`channel_id`, `ak`, `sk`, `auth_version`, `create_by`, `modify_by`) VALUES ('\'${CHANNEL_ID}\'', '\'${AK}\'', '\'${SK}\'', '\'"ROC-HmacSHA256-1.0"\'', '\'${BY}\'', '\'${BY}\'')
	'
fi;
${MYSQL_LAKE} lk_${FACTORY} -e'SELECT * FROM `sys_channel_auth` WHERE `channel_id` = '${CHANNEL_ID} | cat
